<!--
 * 办公/通知 列表
 *
 * @author tqfeiyang
 * @since 2024-09-12
-->
<template>
  <a-form class="smart-query-form" v-privilege="'oa:notice:query'">
      <a-row class="smart-query-form-row">
        <a-form-item label="关键字" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.keywords" placeholder="请输入关键字" />
        </a-form-item>
          <a-form-item class="smart-query-form-item smart-margin-left10">
              <a-button-group>
                  <a-button type="primary" @click="onQuerySubmit">
                      <template #icon>
                          <SearchOutlined />
                      </template>
                      查询
                  </a-button>
                  <a-button @click="onQueryReset">
                      <template #icon>
                          <ReloadOutlined />
                      </template>
                      重置
                  </a-button>
              </a-button-group>
          </a-form-item>
      </a-row>
  </a-form>

  <a-card size="small" :bordered="false">
      <a-row class="smart-table-btn-block">
          <div class="smart-table-operate-block">
              <a-button type="primary" @click="addOrUpdate()">
                  <template #icon>
                      <PlusOutlined />
                  </template>
                  新建
              </a-button>

              <a-button type="primary" danger @click="batchDelete" :disabled="!hasSelected">
                  <template #icon>
                      <DeleteOutlined />
                  </template>
                  批量删除
              </a-button>
          </div>
          <div class="smart-table-setting-block">
              <TableOperator v-model="tableColumns" :refresh="getNoticePage" />
          </div>
      </a-row>

      <a-table
          rowKey="noticeId"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :columns="tableColumns"
          :data-source="tableData"
          :pagination="false"
          :loading="tableLoading"
          @change="onTableChange"
          size="small"
          bordered
      >
          <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'priority'">
                <a-tag v-if="record.priority == 'LOW'" color="success">低</a-tag>
                <a-tag v-if="record.priority == 'MEDIUM'" color="warning">中</a-tag>
                <a-tag v-if="record.priority == 'HIGH'" color="error">高</a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                      <a-button type="link" @click="addOrUpdate(record.noticeId)" v-privilege="'oa:notice:update'">编辑</a-button>
                      <a-button type="link" @click="singleDelete(record)" v-privilege="'oa:notice:delete'" danger>删除</a-button>
                  </div>
              </template>
          </template>
      </a-table>
      
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="tableTotal"
          @change="getNoticePage"
          @showSizeChange="getNoticePage"
          :show-total="(total) => `共${total}条`"
        />
      </div>
  </a-card>

  <NoticeDrawer ref="noticeDrawer" @reloadList="getNoticePage" />
</template>

<script setup>
import { reactive, ref, computed, onMounted, createVNode } from 'vue';
import { message, Modal } from 'ant-design-vue';
import _ from 'lodash';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { smartSentry } from '/@/lib/smart-sentry';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import NoticeDrawer from './components/notice-drawer.vue';
import { noticeApi } from '/@/api/office/notice-api';

// -------------------- 查询 --------------------

const tableData = ref([]);
const tableTotal = ref(0);
const tableLoading = ref(false);

const tableColumns = ref([
  {
    title: '通知id',
    dataIndex: 'noticeId',
    sorter: true,
    sortDirections: ['ascend', 'descend'],
  },
  {
    title: '标题',
    dataIndex: 'title',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '优先级',
    dataIndex: 'priority', //['priority', 'description'],
    orderBy: 'priority',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '分类',
    dataIndex: 'categoryName',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '排序',
    dataIndex: 'sort',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    sorter: true,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 120,
  },
]);

const queryFormState = {
  pageNum: 1,
  pageSize: PAGE_SIZE,
  orderBy: null,
  direction: null,
  keywords: undefined, //关键字
};

const queryForm = reactive({ ...queryFormState });

onMounted(() => {
  getNoticePage();
});

function onQuerySubmit() {
  queryForm.pageNum = 1;
  getNoticePage();
}

function onQueryReset() {
  Object.assign(queryForm, queryFormState);
  getNoticePage();
}

function onTableChange(pagination, filters, sorter) {
  console.log('sorter', sorter, _.join(sorter.field, '.'))
  queryForm.orderBy = sorter.column.orderBy ?? sorter.field;
  queryForm.direction = sorter.order;
  getNoticePage();
}

async function getNoticePage() {
  try {
    tableLoading.value = true;
    const result = await noticeApi.getNoticePage(queryForm)
    tableData.value = result.data.list;
    tableTotal.value = result.data.total;
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    tableLoading.value = false;
  }
}

// -------------------- 多选 --------------------

const selectedRowKeys = ref([]);
const hasSelected = computed(() => selectedRowKeys.value.length > 0);

let selectedRows = [];

function onSelectChange(keyArray, selectRows) {
  selectedRowKeys.value = keyArray;
  selectedRows = selectRows;
}

// ----------------- 新建/编辑 ------------------

const noticeDrawer = ref();

function addOrUpdate(noticeId) {
  console.log('addOrUpdate', noticeId)
    noticeDrawer.value.showModal(noticeId);
}

// -------------------- 删除 --------------------

function singleDelete(record) {
  confirmDelete([record]);
}

function batchDelete() {
  confirmDelete(selectedRows);
}

function confirmDelete(rows) {
  const titles = rows.map((e) => e.title);
  Modal.confirm({
    title: '确定要删除如下数据吗?',
    icon: createVNode(ExclamationCircleOutlined),
    content: _.join(titles, '、'),
    okText: '删除',
    okType: 'danger',
    onOk() {
      const noticeIds = rows.map((e) => e.noticeId);
      batchDeleteNotices(noticeIds);
      selectedRows = [];
      selectedRowKeys.value = [];
    },
    cancelText: '取消',
    onCancel() {},
  });
}

async function batchDeleteNotices(noticeIds) {
  try {
    SmartLoading.show();
    await noticeApi.batchDeleteNotices(noticeIds);
    message.success('删除成功!');
    getNoticePage();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
</script>

<style lang="less" scoped>
</style>
